//
//  VPImageCropperViewController.m
//  VPolor
//
//  Created by Vinson.D.Warm on 12/30/13.
//  Copyright (c) 2013 Huang Vinson. All rights reserved.
//

#import "VPImageCropperViewController.h"


#define SCALE_FRAME_Y 100.0f
#define BOUNDCE_DURATION 0.3f


typedef enum {
    YWImageOrientationUp,
    YWImageOrientationDown,
    YWImageOrientationLeft,
    YWImageOrientationRgiht
}YWImageOrientation;

@interface VPImageCropperViewController ()

@property (nonatomic, strong) UIImage *originalImage;
@property (nonatomic, strong) UIImage *editedImage;

@property (nonatomic, strong) UIImageView *showImgView;
@property (nonatomic, strong) UIView *overlayView;
@property (nonatomic, strong) UIView *ratioView;

@property (nonatomic, assign) CGRect oldFrame;
@property (nonatomic, assign) CGRect largeFrame;
@property (nonatomic, assign) CGFloat limitRatio;

@property (nonatomic, assign) CGRect latestFrame;
@property (nonatomic, assign)YWImageOrientation imageOrientation;


@end

@implementation VPImageCropperViewController

- (void)dealloc {
    self.originalImage = nil;
    self.showImgView = nil;
    self.editedImage = nil;
    self.overlayView = nil;
    self.ratioView = nil;
}

- (id)initWithImage:(UIImage *)originalImage cropFrame:(CGRect)cropFrame limitScaleRatio:(NSInteger)limitRatio {
    self = [super init];
    if (self) {
        self.imageOrientation = YWImageOrientationUp;
        self.cropFrame = cropFrame;
        self.limitRatio = limitRatio;
        self.originalImage = [self fixOrientation:originalImage];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.view.clipsToBounds = YES;
    [self initView];
    [self initControlBtn];
    [self initTurnOffBtn];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self showImageAndOverlayView];
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.overlayView removeFromSuperview];
    self.overlayView = nil;
}

- (void)initTurnOffBtn{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"lan_shut"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(turnOff) forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(11, 25, 40, 40)];
    [self.view addSubview:btn];
}

- (void)changeAction:(UIButton *)btn{
//    self.showImgView.boundsSize = CGSizeMake(320, 480);
  
//
//    switch (self.imageOrientation) {
//        case YWImageOrientationUp:
//            self.imageOrientation = YWImageOrientationRgiht;
//            self.showImgView.transform = CGAffineTransformMakeRotation(M_PI / 2);
//            break;
//        case YWImageOrientationRgiht:
//            self.imageOrientation = YWImageOrientationDown;
//            self.showImgView.transform = CGAffineTransformMakeRotation(0);
//            break;
//        case YWImageOrientationDown:
//            self.imageOrientation = YWImageOrientationLeft;
//            self.showImgView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
//            break;
//        case YWImageOrientationLeft:
//            self.imageOrientation = YWImageOrientationUp;
//            self.showImgView.transform = CGAffineTransformMakeRotation(M_PI);
//            break;
//        default:
//            self.imageOrientation = YWImageOrientationUp;
//            self.showImgView.transform = CGAffineTransformMakeRotation(M_PI);
//            break;
//    }
    if (btn.tag == 20){
        self.originalImage = [self turnRightImageOrientationWithImage:self.originalImage];
    }else{
        self.originalImage = [self tuenLeftImageOrientationWithImage:self.originalImage];
    }
    
    
    self.showImgView.image = self.originalImage;

    CGRect newFrame = self.showImgView.frame;

    newFrame = [self handleScaleOverflow:newFrame];
    newFrame = [self handleBorderOverflow:newFrame];
    [UIView animateWithDuration:BOUNDCE_DURATION animations:^{
        self.showImgView.frame = newFrame;
        self.latestFrame = newFrame;
    }];
    
    
    CGFloat imageWidth = self.originalImage.size.width;
    CGFloat imageHieght = self.originalImage.size.height;
    
    if (self.originalImage.imageOrientation == UIImageOrientationUp || self.originalImage.imageOrientation == UIImageOrientationDown){
        if (imageHieght < imageWidth){
            CGFloat newscale = imageWidth / imageHieght;
            [self setScale:newscale];
        }
    }
    
    if (self.originalImage.imageOrientation == UIImageOrientationLeft || self.originalImage.imageOrientation == UIImageOrientationRight){
        if (imageWidth < imageHieght){
            CGFloat newscale = imageHieght / imageWidth;
            [self setScale:newscale];
        }
    }

    
//    CGFloat oriWidth = self.cropFrame.size.width;
//    CGFloat oriHeight = self.originalImage.size.height * (oriWidth / self.originalImage.size.width);
    
//    if (self.showImgView.frame.size.width < self.cropFrame.size.width){
//        CGFloat newScale = self.cropFrame.size.width / self.showImgView.frame.size.width;
//        [self setScale:newScale];
//    }
//    if (oriHeight < self.cropFrame.size.height){
//        CGFloat scale = self.cropFrame.size.height / oriHeight;
//        [self setScale:scale];
//    }
    
    
//    CGFloat oriHeight1 = self.cropFrame.size.height;
//    CGFloat oriWidth1 = self.originalImage.size.width * (oriHeight1 / self.originalImage.size.height);
//    
//    if (oriWidth1 < self.cropFrame.size.width){
//        CGFloat scale = self.cropFrame.size.width / oriWidth1;
//        [self setScale:scale];
//    }
    
}

- (void)turnOff{
    if ([self.delegate respondsToSelector:@selector(imageCropperDidTurnOff:)]){
        [self.delegate imageCropperDidTurnOff:self];
    }
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return NO;
}

- (void)initView {
    self.view.backgroundColor = [UIColor blackColor];
    
    self.showImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    [self.showImgView setMultipleTouchEnabled:YES];
    [self.showImgView setUserInteractionEnabled:YES];
    [self.showImgView setUserInteractionEnabled:YES];
    [self.showImgView setMultipleTouchEnabled:YES];
    [self.showImgView setImage:self.originalImage];

    
    // scale to fit the screen
    CGFloat oriWidth = self.cropFrame.size.width;
    CGFloat oriHeight = self.originalImage.size.height * (oriWidth / self.originalImage.size.width);
    CGFloat oriX = self.cropFrame.origin.x + (self.cropFrame.size.width - oriWidth) / 2;
    CGFloat oriY = self.cropFrame.origin.y + (self.cropFrame.size.height - oriHeight) / 2;
    
    self.oldFrame = CGRectMake(oriX, oriY, oriWidth, oriHeight);
    self.latestFrame = self.oldFrame;
    self.showImgView.frame = self.oldFrame;
    
    
    
    self.largeFrame = CGRectMake(0, 0, self.limitRatio * self.oldFrame.size.width, self.limitRatio * self.oldFrame.size.height);
    
    [self addGestureRecognizers];
    if (oriHeight < self.cropFrame.size.height){
        CGFloat scale = self.cropFrame.size.height / oriHeight;
        [self setScale:scale];
    }
    [self.view addSubview:self.showImgView];
    
    //背景黑色

   //
    //截取的范围
    self.ratioView = [[UIView alloc] initWithFrame:self.cropFrame];
    self.ratioView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.ratioView.layer.borderWidth = 1.0f;
    self.ratioView.autoresizingMask = UIViewAutoresizingNone;
    [self.view addSubview:self.ratioView];
    
}

- (void)showImageAndOverlayView{
    if (self.overlayView == nil){
        self.overlayView = [[UIView alloc] initWithFrame:self.view.bounds];
        self.overlayView.alpha = .5f;
        self.overlayView.backgroundColor = [UIColor blackColor];
        self.overlayView.userInteractionEnabled = NO;
        self.overlayView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        //    [self.view addSubview:self.overlayView];
        [self.view insertSubview:self.overlayView aboveSubview:self.showImgView];
        [UIView animateWithDuration:0.2 animations:^{
            [self overlayClipping];
        }];
    }
}

- (void)initControlBtn {
    NSInteger height = kScreenHeight - 96 - kScreenWidth;
    
    NSInteger centerY = kScreenWidth + 96 + height / 2;
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, self.view.boundsHeight - 40, 50, 50)];
    [cancelBtn setImage:[UIImage imageNamed:@"topic_abandon"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.centerY = centerY;
    [self.view addSubview:cancelBtn];
    
    UIButton *confirmBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.boundsWidth - 50, self.view.boundsHeight - 40, 50, 50)];
    [confirmBtn setImage:[UIImage imageNamed:@"topic_finishe"] forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirm:) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.centerY = centerY;
    [self.view addSubview:confirmBtn];
    
    NSInteger centerX = kScreenWidth/2;
    
    UIButton * turnLeft = [UIButton buttonWithType:UIButtonTypeCustom];
    turnLeft.tag = 10;
    [turnLeft setImage:[UIImage imageNamed:@"crop_left"] forState:UIControlStateNormal];
    [turnLeft setFrame:CGRectMake(centerX - 60, self.view.boundsHeight - 50, 50, 50)];
    [turnLeft addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventTouchUpInside];
    turnLeft.centerY = centerY;
    [self.view addSubview:turnLeft];
    
    UIButton * turnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    turnRight.tag = 20;
    [turnRight setImage:[UIImage imageNamed:@"crop_right"] forState:UIControlStateNormal];
    [turnRight setFrame:CGRectMake(centerX + 10, self.view.boundsHeight - 50, 50, 50)];
    [turnRight addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventTouchUpInside];
    turnRight.centerY = centerY;
    [self.view addSubview:turnRight];
}


- (void)cancel:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    if (self.delegate && [self.delegate conformsToProtocol:@protocol(VPImageCropperDelegate)]) {
        [self.delegate imageCropperDidCancel:self];
    }
}

- (void)confirm:(id)sender {
//    PhotoAddFilterViewController * photoAddFilterViewController = [[PhotoAddFilterViewController alloc]init];
//    UIImage * newImage = [self getSubImage];
//    photoAddFilterViewController.image = newImage;
//    [self.navigationController pushViewController:photoAddFilterViewController animated:YES];
    
    if (self.delegate && [self.delegate conformsToProtocol:@protocol(VPImageCropperDelegate)]) {
        [self.delegate imageCropper:self didFinished:[self getSubImage]];
    }
}

- (void)overlayClipping
{
    //差不多意思就是切出一块白色。
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef path = CGPathCreateMutable();
    // Left side of the ratio view
    CGPathAddRect(path, nil, CGRectMake(0, 0,
                                        self.ratioView.frame.origin.x,
                                        self.overlayView.frame.size.height));
    // Right side of the ratio view
    CGPathAddRect(path, nil, CGRectMake(
                                        self.ratioView.frame.origin.x + self.ratioView.frame.size.width,
                                        0,
                                        self.overlayView.frame.size.width - self.ratioView.frame.origin.x - self.ratioView.frame.size.width,
                                        self.overlayView.frame.size.height));
    // Top side of the ratio view
    CGPathAddRect(path, nil, CGRectMake(0, 0,
                                        self.overlayView.frame.size.width,
                                        self.ratioView.frame.origin.y));
    // Bottom side of the ratio view
    CGPathAddRect(path, nil, CGRectMake(0,
                                        self.ratioView.frame.origin.y + self.ratioView.frame.size.height,
                                        self.overlayView.frame.size.width,
                                        self.overlayView.frame.size.height - self.ratioView.frame.origin.y + self.ratioView.frame.size.height));
    maskLayer.path = path;
    self.overlayView.layer.mask = maskLayer;
    CGPathRelease(path);
}

// register all gestures
- (void) addGestureRecognizers
{
    // add pinch gesture
    UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchView:)];
    [self.view addGestureRecognizer:pinchGestureRecognizer];
    
    // add pan gesture
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)];
    [self.view addGestureRecognizer:panGestureRecognizer];
}

// pinch gesture handler
- (void)setScale:(CGFloat)newScale{
    UIView *view = self.showImgView;
    view.transform = CGAffineTransformScale(view.transform, newScale, newScale);
    CGRect newFrame = self.showImgView.frame;
    newFrame = [self handleScaleOverflow:newFrame];
    newFrame = [self handleBorderOverflow:newFrame];
    [UIView animateWithDuration:BOUNDCE_DURATION animations:^{
        self.showImgView.frame = newFrame;
        self.latestFrame = newFrame;
        self.oldFrame = newFrame;
    }];
}

- (void) pinchView:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
    UIView *view = self.showImgView;
    if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan || pinchGestureRecognizer.state == UIGestureRecognizerStateChanged) {
        view.transform = CGAffineTransformScale(view.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);
        pinchGestureRecognizer.scale = 1;
    }
    else if (pinchGestureRecognizer.state == UIGestureRecognizerStateEnded) {
        CGRect newFrame = self.showImgView.frame;
        newFrame = [self handleScaleOverflow:newFrame];
        newFrame = [self handleBorderOverflow:newFrame];
        [UIView animateWithDuration:BOUNDCE_DURATION animations:^{
            self.showImgView.frame = newFrame;
            self.latestFrame = newFrame;
        }];
    }
}

// pan gesture handler
- (void) panView:(UIPanGestureRecognizer *)panGestureRecognizer
{
    UIView *view = self.showImgView;
    if (panGestureRecognizer.state == UIGestureRecognizerStateBegan || panGestureRecognizer.state == UIGestureRecognizerStateChanged) {
        // calculate accelerator
        CGFloat absCenterX = self.cropFrame.origin.x + self.cropFrame.size.width / 2;
        CGFloat absCenterY = self.cropFrame.origin.y + self.cropFrame.size.height / 2;
        CGFloat scaleRatio = self.showImgView.frame.size.width / self.cropFrame.size.width;
        CGFloat acceleratorX = 1 - ABS(absCenterX - view.center.x) / (scaleRatio * absCenterX);
        CGFloat acceleratorY = 1 - ABS(absCenterY - view.center.y) / (scaleRatio * absCenterY);
        CGPoint translation = [panGestureRecognizer translationInView:view.superview];
        [view setCenter:(CGPoint){view.center.x + translation.x * acceleratorX, view.center.y + translation.y * acceleratorY}];
        [panGestureRecognizer setTranslation:CGPointZero inView:view.superview];
    }
    else if (panGestureRecognizer.state == UIGestureRecognizerStateEnded) {
        // bounce to original frame
        CGRect newFrame = self.showImgView.frame;
        newFrame = [self handleBorderOverflow:newFrame];
        [UIView animateWithDuration:BOUNDCE_DURATION animations:^{
            self.showImgView.frame = newFrame;
            self.latestFrame = newFrame;
        }];
    }
}

- (CGRect)handleScaleOverflow:(CGRect)newFrame {
    // bounce to original frame
    CGPoint oriCenter = CGPointMake(newFrame.origin.x + newFrame.size.width/2, newFrame.origin.y + newFrame.size.height/2);
    if (newFrame.size.width < self.oldFrame.size.width) {
        newFrame = self.oldFrame;
    }
    if (newFrame.size.width > self.largeFrame.size.width) {
        newFrame = self.largeFrame;
    }
    newFrame.origin.x = oriCenter.x - newFrame.size.width/2;
    newFrame.origin.y = oriCenter.y - newFrame.size.height/2;
    return newFrame;
}

- (CGRect)handleBorderOverflow:(CGRect)newFrame {
    // horizontally
    if (newFrame.origin.x > self.cropFrame.origin.x) newFrame.origin.x = self.cropFrame.origin.x;
    if (CGRectGetMaxX(newFrame) < self.cropFrame.size.width) newFrame.origin.x = self.cropFrame.size.width - newFrame.size.width;
    // vertically
    if (newFrame.origin.y > self.cropFrame.origin.y) newFrame.origin.y = self.cropFrame.origin.y;
    if (CGRectGetMaxY(newFrame) < self.cropFrame.origin.y + self.cropFrame.size.height) {
        newFrame.origin.y = self.cropFrame.origin.y + self.cropFrame.size.height - newFrame.size.height;
    }
    // adapt horizontally rectangle
    if (self.showImgView.frame.size.width > self.showImgView.frame.size.height && newFrame.size.height <= self.cropFrame.size.height) {
        newFrame.origin.y = self.cropFrame.origin.y + (self.cropFrame.size.height - newFrame.size.height) / 2;
    }
    return newFrame;
}


- (UIImage *) cropImage:(UIImage *)originalImage withRect:(CGRect)rect
{
    //calculate scale factor to go between cropframe and original image
    CGAffineTransform rectTransform;
    switch (originalImage.imageOrientation)
    {
        case UIImageOrientationLeft:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(M_PI_2), 0, -originalImage.size.height);
            break;
        case UIImageOrientationRight:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(-M_PI_2), -originalImage.size.width, 0);
            break;
        case UIImageOrientationDown:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(-M_PI), -originalImage.size.width, -originalImage.size.height);
            break;
        default:
            rectTransform = CGAffineTransformIdentity;
    };
    rectTransform = CGAffineTransformScale(rectTransform, originalImage.scale, originalImage.scale);
    
    
    CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], CGRectApplyAffineTransform(rect, rectTransform));
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:originalImage.scale orientation:originalImage.imageOrientation];
    CGImageRelease(imageRef);
    
    return result;
}

-(UIImage *)getSubImage{
    CGRect squareFrame = self.cropFrame;
    CGFloat scaleRatio = self.latestFrame.size.width / self.originalImage.size.width;
    CGFloat x = (squareFrame.origin.x - self.latestFrame.origin.x) / scaleRatio;
    CGFloat y = (squareFrame.origin.y - self.latestFrame.origin.y) / scaleRatio;
    CGFloat w = squareFrame.size.width / scaleRatio;
    CGFloat h = squareFrame.size.height / scaleRatio;
    if (self.latestFrame.size.width < self.cropFrame.size.width) {
        CGFloat newW = self.originalImage.size.width;
        CGFloat newH = newW * (self.cropFrame.size.height / self.cropFrame.size.width);
        x = 0; y = y + (h - newH) / 2;
        w = newH; h = newH;
    }
    if (self.latestFrame.size.height < self.cropFrame.size.height) {
        CGFloat newH = self.originalImage.size.height;
        CGFloat newW = newH * (self.cropFrame.size.width / self.cropFrame.size.height);
        x = x + (w - newW) / 2; y = 0;
        w = newH; h = newH;
    }
    CGRect myImageRect = CGRectMake(x, y, w, h);
    
    UIImage * fixImage = [self fixOrientation:self.originalImage];
    CGImageRef imageRef = fixImage.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, myImageRect);
    CGSize size;
    size.width = myImageRect.size.width;
    size.height = myImageRect.size.height;
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, myImageRect, subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef scale:1.0f orientation:fixImage.imageOrientation];
    CGImageRelease(subImageRef);
    UIGraphicsEndImageContext();
    return smallImage;
}

- (UIImage *)tuenLeftImageOrientationWithImage:(UIImage *)originalImage{
    CGFloat oriWidth = self.cropFrame.size.width;
    CGFloat oriHeight = self.originalImage.size.height * (oriWidth / self.originalImage.size.width);
    CGFloat oriX = self.cropFrame.origin.x + (self.cropFrame.size.width - oriWidth) / 2;
    CGFloat oriY = self.cropFrame.origin.y + (self.cropFrame.size.height - oriHeight) / 2;
    
    UIImage *imageToDisplay = nil;
    if ([originalImage imageOrientation] == UIImageOrientationUp){
        imageToDisplay = [UIImage imageWithCGImage:[originalImage CGImage]
                                             scale:0.0
                                       orientation: UIImageOrientationLeft];
        
        self.oldFrame = CGRectMake(oriX, oriY, oriHeight, oriWidth);
    }else if ([originalImage imageOrientation] == UIImageOrientationRight){
        imageToDisplay = [UIImage imageWithCGImage:[originalImage CGImage]
                                             scale:0.0
                                       orientation: UIImageOrientationUp];
        oriHeight = imageToDisplay.size.height * (oriWidth / imageToDisplay.size.width);
        CGFloat oriY = self.cropFrame.origin.y + (self.cropFrame.size.height - oriHeight) / 2;
        self.oldFrame = CGRectMake(oriX, oriY, oriWidth, oriHeight);
    }else if ([originalImage imageOrientation] == UIImageOrientationDown){
        imageToDisplay = [UIImage imageWithCGImage:[originalImage CGImage]
                                             scale:0.0
                                       orientation: UIImageOrientationRight];
        self.oldFrame = CGRectMake(oriX, oriY, oriHeight, oriWidth);
    }else if ([originalImage imageOrientation] == UIImageOrientationLeft){
        imageToDisplay = [UIImage imageWithCGImage:[originalImage CGImage]
                                             scale:0.0
                                       orientation: UIImageOrientationDown];
        oriHeight = imageToDisplay.size.height * (oriWidth / imageToDisplay.size.width);
        CGFloat oriY = self.cropFrame.origin.y + (self.cropFrame.size.height - oriHeight) / 2;
        self.oldFrame = CGRectMake(oriX, oriY, oriWidth, oriHeight);
    }
    self.largeFrame = CGRectMake(0, 0, self.limitRatio * self.oldFrame.size.width, self.limitRatio * self.oldFrame.size.height);
    self.showImgView.frame = self.oldFrame;
    return imageToDisplay;
}

- (UIImage *)turnRightImageOrientationWithImage:(UIImage *)originalImage{
    CGFloat oriWidth = self.cropFrame.size.width;
    CGFloat oriHeight = self.originalImage.size.height * (oriWidth / self.originalImage.size.width);
    CGFloat oriX = self.cropFrame.origin.x + (self.cropFrame.size.width - oriWidth) / 2;
    CGFloat oriY = self.cropFrame.origin.y + (self.cropFrame.size.height - oriHeight) / 2;
    
    UIImage *imageToDisplay = nil;
    if ([originalImage imageOrientation] == UIImageOrientationUp){
        imageToDisplay = [UIImage imageWithCGImage:[originalImage CGImage]
                                     scale:0.0
                               orientation: UIImageOrientationRight];
        
        self.oldFrame = CGRectMake(oriX, oriY, oriHeight, oriWidth);
    }else if ([originalImage imageOrientation] == UIImageOrientationRight){
        imageToDisplay = [UIImage imageWithCGImage:[originalImage CGImage]
                                             scale:0.0
                                       orientation: UIImageOrientationDown];
        oriHeight = imageToDisplay.size.height * (oriWidth / imageToDisplay.size.width);
        CGFloat oriY = self.cropFrame.origin.y + (self.cropFrame.size.height - oriHeight) / 2;
        self.oldFrame = CGRectMake(oriX, oriY, oriWidth, oriHeight);
    }else if ([originalImage imageOrientation] == UIImageOrientationDown){
        imageToDisplay = [UIImage imageWithCGImage:[originalImage CGImage]
                                             scale:0.0
                                       orientation: UIImageOrientationLeft];
        self.oldFrame = CGRectMake(oriX, oriY, oriHeight, oriWidth);
    }else if ([originalImage imageOrientation] == UIImageOrientationLeft){
        imageToDisplay = [UIImage imageWithCGImage:[originalImage CGImage]
                                             scale:0.0
                                       orientation: UIImageOrientationUp];
        oriHeight = imageToDisplay.size.height * (oriWidth / imageToDisplay.size.width);
        CGFloat oriY = self.cropFrame.origin.y + (self.cropFrame.size.height - oriHeight) / 2;
        self.oldFrame = CGRectMake(oriX, oriY, oriWidth, oriHeight);
    }
    self.largeFrame = CGRectMake(0, 0, self.limitRatio * self.oldFrame.size.width, self.limitRatio * self.oldFrame.size.height);
    self.showImgView.frame = self.oldFrame;
    return imageToDisplay;
}

- (UIImage *)fixOrientation:(UIImage *)srcImg {
    if (srcImg.imageOrientation == UIImageOrientationUp) return srcImg;
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (srcImg.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, srcImg.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, srcImg.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (srcImg.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, srcImg.size.width, srcImg.size.height,
                                             CGImageGetBitsPerComponent(srcImg.CGImage), 0,
                                             CGImageGetColorSpace(srcImg.CGImage),
                                             CGImageGetBitmapInfo(srcImg.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (srcImg.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.height,srcImg.size.width), srcImg.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.width,srcImg.size.height), srcImg.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

@end
